<!--  -->
<template>
  <!--  导入信息页面-->
  <div class="importBg">
    <div class="firstLevel content">
      <el-tabs v-model="activeName" >
        <el-tab-pane label="区间档案" name="quJian">
          <div class="conContent">
            <el-divider><span style="color: #1990FE;font-size: 20px">区间数据导入</span></el-divider>
            <br/>
            <el-upload class="upload-demo" ref="quJian" :action="constUrl + '/common/upload/v1/importRoadSection/'+uuid" drag :limit="1"
                       :file-list="quJian.uploadFile"
                       :before-upload="beforeUpload"
                       :on-exceed="_handleExceed"
                       :on-success="_uploadSuccess"
                       :on-remove="_uploadRemove"
                       :auto-upload="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
                <div class="el-upload__tip" slot="tip">只能上传{{quJian.fileType.toString()}}格式文件，且不超过1M</div>
              </div>
            </el-upload>
            <br/>
            <div style="width: 50%;margin: auto; margin-bottom: 1vw;" v-if="quJian.percentage!==0">
              <el-progress :text-inside="true" :stroke-width="26" :percentage="quJian.percentage"></el-progress>
            </div>
            <el-button icon="el-icon-download" @click.stop="handleOutFile" type="primary" style="background:#4caf50 ">
              导入模板下载
            </el-button>
            <el-button type="primary" @click="validateFormFile('quJian')">立即导入</el-button>
            <el-popconfirm title="重新导入会清空导入文件和错误文件，是否确认？" style="margin-right: 16px"
                           @confirm="refresh">
              <el-button type="primary" style="background:#e91e63;margin-left: 0.5vw" slot="reference">重新导入</el-button>
            </el-popconfirm>
            <div class="upload_res_view"  v-if="quJian.successCount || quJian.errorCount">
              <div style="padding: 20px">
                文件导入完成！数据总数：{{quJian.errorCount + quJian.successCount}},<span style="color: #0bb20c">导入成功：{{quJian.successCount}}条;</span>
                <span style="color: #ff4d51">导入失败:{{quJian.errorCount}}条</span>
              </div>
              <a style="margin-left: 20px" v-if="quJian.errorCount!==0" :href="constUrl + quJian.errFileUrl">
                <el-button icon="el-icon-download" type="primary" style="background:#e91e63 ">失败文件下载</el-button>
              </a>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="地质灾害档案" name="diZhi">
          <div class="conContent">
            <el-divider><span style="color: #1990FE;font-size: 20px">地质灾害数据导入</span></el-divider>
            <br/>
            <el-upload class="upload-demo" ref="diZhi" :action="constUrl + '/common/upload/v1/importDamageInfo/'+uuid" drag :limit="1"
                       :file-list="diZhi.uploadFile"
                       :before-upload="beforeUpload"
                       :on-exceed="_handleExceed"
                       :on-success="_uploadSuccess"
                       :auto-upload="false"
                       :on-remove="_uploadRemove">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
                <div class="el-upload__tip" slot="tip">只能上传{{diZhi.fileType.toString()}}格式文件，且不超过1M</div>
              </div>
            </el-upload>
            <br/>
            <div style="width: 50%;margin: auto; margin-bottom: 1vw;" v-if="diZhi.percentage!==0">
              <el-progress :text-inside="true" :stroke-width="26" :percentage="diZhi.percentage"></el-progress>

            </div>
            <el-button icon="el-icon-download" @click.stop="handleOutFile" type="primary" style="background:#4caf50 ">
              导入模板下载
            </el-button>
            <el-button type="primary" @click="validateFormFile('diZhi')">立即导入</el-button>
            <el-popconfirm title="重新导入会清空导入文件和错误文件，是否确认？" style="margin-right: 16px"
                           @confirm="refresh">
              <el-button type="primary" style="background:#e91e63;margin-left: 0.5vw" slot="reference">重新导入</el-button>
            </el-popconfirm>
            <div class="upload_res_view" v-if="diZhi.successCount || diZhi.errorCount">
              <div style="padding: 20px">
                文件导入完成！数据总数：{{diZhi.errorCount + diZhi.successCount}},<span style="color: #0bb20c">导入成功：{{diZhi.successCount}}条;</span>
                <span style="color: #ff4d51">导入失败:{{diZhi.errorCount}}条</span>
              </div>
              <a style="margin-left: 20px" v-if="diZhi.errorCount!==0" :href="constUrl + diZhi.errFileUrl">
                <el-button icon="el-icon-download" type="primary" style="background:#e91e63 ">失败文件下载</el-button>
              </a>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="边坡档案" name="bianPo">
          <div class="conContent">
            <el-divider><span style="color: #1990FE;font-size: 20px">边坡数据导入</span></el-divider>
            <br/>
            <el-upload class="upload-demo" ref="bianPo" :action="constUrl + '/common/upload/v1/importSlopeInfo/'+uuid" drag :limit="1"
                       :file-list="bianPo.uploadFile"
                       :before-upload="beforeUpload"
                       :on-exceed="_handleExceed"
                       :on-success="_uploadSuccess"
                       :on-remove="_uploadRemove"
              :auto-upload="false"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
                <div class="el-upload__tip" slot="tip">只能上传{{bianPo.fileType.toString()}}格式文件，且不超过1M</div>
              </div>
            </el-upload>
            <br/>
            <div style="width: 50%;margin: auto; margin-bottom: 1vw;" v-if="percentage!==0">
              <el-progress :text-inside="true" :stroke-width="26" :percentage="bianPo.percentage"></el-progress>

            </div>
            <el-button icon="el-icon-download" @click.stop="handleOutFile" type="primary" style="background:#4caf50 ">
              导入模板下载
            </el-button>
            <el-button type="primary" @click="validateFormFile('bianPo')">立即导入</el-button>
            <el-popconfirm title="重新导入会清空导入文件和错误文件，是否确认？" style="margin-right: 16px"
                           @confirm="refresh">
              <el-button type="primary" style="background:#e91e63;margin-left: 0.5vw" slot="reference">重新导入</el-button>
            </el-popconfirm>
            <div class="upload_res_view" v-if="bianPo.successCount || bianPo.errorCount">
              <div style="padding: 20px">
                文件导入完成！数据总数：{{bianPo.errorCount + bianPo.successCount}},<span style="color: #0bb20c">导入成功：{{bianPo.successCount}}条;</span>
                <span style="color: #ff4d51">导入失败:{{bianPo.errorCount}}条</span>
              </div>
              <a style="margin-left: 20px" v-if="bianPo.errorCount!==0" :href="constUrl + bianPo.errFileUrl">
                <el-button icon="el-icon-download" type="primary" style="background:#e91e63 ">失败文件下载</el-button>
              </a>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <x-loading v-show="isLoading"></x-loading>
    </div>
  </div>
</template>

<script>
import XLoading from '@/components/animation/x-loading.vue'
import constUrl from "../../services/env";
import {
  roadSectionImport,
  damageImport,
  slopeImport
} from '@/services/model/road-mgmt'
import {uploadUrl} from '@/services/model/common'
import {Message} from "element-ui";

export default {
  components: {XLoading},
  data() {
    //这里存放数据
    return {
      uuid:'',
      ws: null,
      percentage:0,

      isLoading: false,
      constUrl,
      uploadStreamUrl: uploadUrl,
      paramFile1: {
        type: ['xlsx'],
        dragInfo: '只能上传后缀为xlsx的excl文件'
      },
      activeName: 'quJian',
      quJian: {//区间导入对象
        uploadFile: [],//上传成功的文件
        fileType: ['xlsx', 'xls'],//支持导入文件类型后缀名
        fileName: '',//导入文件名
        files: null,//导入文件流
        errFileUrl: '',//导入失败返回的文件地址
        successCount: '',//导入成功数量
        errorCount: '',//导入失败数量
        percentage:0
      },
      diZhi: {//地质灾害档案导入对象
        uploadFile: [],//上传成功的文件
        fileType: ['xlsx', 'xls','csv'],//支持导入文件类型后缀名
        fileName: '',//导入文件名
        files: null,//导入文件流
        errFileUrl: '',//导入失败返回的文件地址
        successCount: '',//导入成功数量
        errorCount: '',//导入失败数量
        percentage:0
      },
      bianPo: {//边坡档案导入对象
        uploadFile: [],//上传成功的文件
        fileType: ['xlsx', 'xls','csv'],//支持导入文件类型后缀名
        fileName: '',//导入文件名
        files: null,//导入文件流
        errFileUrl: '',//导入失败返回的文件地址
        successCount: '',//导入成功数量
        errorCount: '',//导入失败数量
        percentage:0
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    refresh(){
      this[`${this.activeName}`]={ uploadFile: [],//上传成功的文件
        fileType: ['xlsx', 'xls','csv'],//支持导入文件类型后缀名
        fileName: '',//导入文件名
        files: null,//导入文件流
        errFileUrl: '',//导入失败返回的文件地址
        successCount: '',//导入成功数量
        errorCount: '',//导入失败数量
        percentage:0
         }
      this.$forceUpdate()
    },
    getUUID() {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = '-'
      var uuid = s.join('')
      return uuid
    },
    // 确认导入文件
    validateFormFile(name) {
      this.$refs[`${name}`].submit();
    },
    connectSocket() {
      this.uuid = this.getUUID();
      let uuid = this.uuid
      if ('WebSocket' in window) {
        // 打开一个 web socket
        // 8.134.64.118:9093
        this.ws = new WebSocket(`ws://8.134.54.223:9999/webSocket/file/upload/${uuid}`)
        this.ws.onopen = function () {
          console.log('websocket 连接上')
        }
        // 连接
        this.ws.onmessage = (evt) => {
          let mes = JSON.parse(evt.data)
          if (mes.code == 200) {
            if(mes.data.percentage){
              let percentage= mes.data.percentage
              this[`${this.activeName}`].percentage=parseFloat((percentage*100).toFixed(2))
            }else {
              this[`${this.activeName}`].percentage=100.00
              this[`${this.activeName}`].errorCount=mes.data.errorCount
             if(mes.data.errorCount!==0){
               this[`${this.activeName}`].errFileUrl=mes.data.errorFileUrl
             }
              this[`${this.activeName}`].successCount=mes.data.successCount
            }

          }else {
            this.$notify({
              type: 'error',
              title: '提示',
              message: mes.message
            })

          }
        }

        this.ws.onerror = function (err) {
        }
      } else {
        // 浏览器不支持 WebSocket
        Message({
          type: 'warning',
          message: '您的浏览器不支持 WebSocket!'
        })
      }
    },
    // 添加文件个数限制
    _handleExceed() {
      // 每次只能提交一个文件
      if (this[`${this.activeName}`].uploadFile?.length >= 1) {
        this.$message.warning('一次只能导入1个文件')
        return false
      }
    },
    beforeUpload(file) { // 上传前 文件校验
      this[`${this.activeName}`].files = file
      const fileType = file.name.split('.')[1]
      const supportFileType = this[`${this.activeName}`].fileType
      const isLt2M = file.size / 1024 / 1024 < 1
      if (supportFileType.indexOf(fileType) === -1) {
        this.$message.warning('上传文件只能是' + supportFileType.toString() + '格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.warning('上传文件大小不能超过 1MB!')
        return false
      }
      this[`${this.activeName}`].fileName = file.name
      return
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    _uploadRemove(file, fileList) {
      this[`${this.activeName}`].uploadFile = fileList
    },
    /**
     * 文件上传成功时的钩子
     */
    _uploadSuccess(res, file, fileList) {
      this[`${this.activeName}`].uploadFile = fileList
    },
    handleOutFile() {
      let tempUrl = ''
      if (this.activeName === 'quJian') {
        tempUrl = '/statics/区间档案导入模板.xls'
      } else if (this.activeName === 'diZhi') {
        tempUrl = '/statics/地质灾害档案导入模板-v1.xls'
      } else if (this.activeName === 'bianPo') {
        tempUrl = '/statics/边坡档案导入模板-v1.xls'
      }
      // 文件导出
      const {href} = this.$router.resolve({path: tempUrl})
      window.open(href)
    }
    ,
  },
  mounted() {
    this.connectSocket()

  },
  beforeDestroy() {
    this.ws.onclose = function (e) { // 监听关闭
      // this.ws.close()
      console.log('连接已关闭...')
    }
  }
};
</script>
<style lang='less' scoped>
  .upload_res_view {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    margin-top: 20px;
    padding: 20px;
    margin-left: 25%;
    width: 50%
  }

  .firstLevel {
    padding: 20px;
    margin: auto;

    /deep/ .el-upload-list__item-name {
      font-size: 20px;
    }

    /deep/ .el-tabs__item {
      color: black;
      width: 100%;
      text-align: center;
      box-sizing: border-box;
      font-size: 16px;
    }

    /deep/ .el-upload {
      width: 100%;
    }

    /deep/ .el-upload-dragger {
      width: 100%;
    }

    /deep/ .el-tabs__item.is-active {
      color: white;
      background-color: #1990FE;
      font-size: 140%;
      box-sizing: border-box;
    }

    /deep/ .el-tabs__active-bar {
      background-color: #1990FE !important;
    }
  }

  .importBg {
    width: 100%;
    height: 100%;
    overflow: auto;

    header {
      width: 80%;
      height: 80px;
      /*background: #1b1b1b;*/
      margin: 10px auto;
      box-sizing: border-box;
      padding: 0 200px;
      padding-top: 20px;
      box-shadow: 0px 0px 8px black;

      display: flex;
      justify-content: space-between;

      .headerLeft {
        width: 70%;
        height: 50px;

        h6 {
          font-size: 30px;
          color: #1990FE;
          font-size: 600;
          height: 50px;
          line-height: 50px;
        }
      }

      .headerRight {
        width: 30%;
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;

        span {
          width: 25%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          box-sizing: border-box;
          border: 1px solid white;
          border: 1px solid #1990FE;
        }

        .isActive {
          width: 25%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          box-sizing: border-box;
          background: #1990FE;
          border: 1px solid #1990FE;
          color: white;
          font-size: 16px;
          font-weight: 600;
        }
      }
    }

    .content {
      margin: 0 auto;
      margin-top: 20px;
      width: 80%;
      height: 800px;
      box-shadow: -2px 2px 8px black;

      .contentHeader {
        border-radius: 15px 15px 0 0;
        border-bottom: 2px solid #505050;
        width: 100%;
        height: 6%;
        box-sizing: border-box;
        padding-left: 50px;
        color: #1990FE;
        line-height: 50px;
      }

      .conContent {
        text-align: center;
        width: 100%;
        height: 92%;
        margin-top: 1%;
        border-radius: 0 0 15px 15px;
        padding: 20px;
        animation: fade_bottom 1.5s;
        @keyframes fade_bottom {
          from {
            transform: translateY(30px);
            opacity: 0.2;
          }
          to {
            transform: translateY(0px);
            opacity: 0.9;
          }
        }
      }
    }
  }
</style>

